package com.goldcontrol.cloudweb.quartz.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.goldcontrol.cloudweb.util.ConstantUtil;
import com.goldcontrol.cloudweb.util.HttpUtil;
import com.goldcontrol.cloudweb.util.StringUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class AccessJcmJob implements Job {

    private Logger logger = LoggerFactory.getLogger(AccessJcmJob.class);

    /*微信公众平台api的基地址*/
    private static final String weixin_url = "https://api.weixin.qq.com/cgi-bin/";

    @Override
    public void execute(JobExecutionContext jobExecutionContext){
        try{
            logger.info("!!!!!!jcm quartz job start.");
            //获取access_token
            String url = weixin_url + "token?grant_type=client_credential&appid=" + ConstantUtil.jcm_appid + "&secret=" + ConstantUtil.jcm_appsecret;
            String accessTokenResult = HttpUtil.get(url);
            logger.info(accessTokenResult);
            logger.error("AccessJcmJob 获取的token 为:{}",accessTokenResult);
            JSONObject jobj = JSON.parseObject(accessTokenResult);
            if(StringUtil.isStrNull(jobj.getString("access_token"))){
                logger.error("!!!!!!access_token is null, get failed. ");
                return;
            }
            ConstantUtil.jcm_access_token = jobj.getString("access_token");

            //获取jsapi_ticket
            url = weixin_url + "ticket/getticket?access_token=" + ConstantUtil.jcm_access_token + "&type=jsapi";
            String jsapiTicketResult = HttpUtil.get(url);
            logger.info(jsapiTicketResult);
            jobj = JSON.parseObject(jsapiTicketResult);
            if(StringUtil.isStrNull(jobj.getString("ticket"))){
                logger.error("!!!!!!jsapi_ticket is null, get failed. ");
                return;
            }
            ConstantUtil.jsapi_ticket = jobj.getString("ticket");

            logger.info("!!!!!!quartz job end.");
        }catch (Exception e){
            logger.error("定时任务控制失败",e);
        }
    }


}
